<template>
  <div class="c">
    <div id="map"></div>
    <div class="layerIcon" @click="showLayerTree">
      <img src="../assets/image/layer.png" />
    </div>
    <layer-manager
      ref="layerManager"
      :treeData="layerTree"
      :class="layerStyle"
    ></layer-manager>
    <div class="btnContainer">
      <el-button @click="addWMTS">加载wmts</el-button>
      <el-button @click="addTiles">加载3dTiles</el-button>
      <el-button @click="addS3M">加载s3m</el-button>
      <el-button @click="sunshine">日照分析</el-button>
      <el-button @click="shootAreaAnalysis">可视域分析</el-button>
      <el-button @click="translation">平移3dTiles</el-button>
      <el-button @click="snow">下雪效果</el-button>
      <el-button @click="pickEntity">拾取</el-button>
      <el-button @click="flat">压平</el-button>
      <el-button @click="draw">绘制</el-button>
    </div>
    <sun-shine v-if="sunshineVisible"></sun-shine>
    <visual-area v-if="visualAreaVisible"></visual-area>
  </div>
</template>

<script>
/* eslint-disable */
import { layerInfo } from "../views/layerManager/other/layerData";
import sunShine from "../components/sunshine.vue";
import VisualArea from "../components/Visualarea.vue";
import { iserverUrl, imageMap, notesMap } from "./configs/index.config.js";
import layerManager from "./layerManager/index.vue";
import layerManagerClass from "../views/layerManager/util/layerManager";
import CesiumDraw from "./util/cesiumDraw/index";
export default {
  name: "Home",
  components: { sunShine, VisualArea, layerManager },
  data() {
    return {
      sunshineVisible: false,
      visualAreaVisible: false,
      layerStyle: "enter-before",
      layerTree: [],
      postProcessStages: null,
      flatExtent: [],
      points: [],
      features: [],
    };
  },
  created() {
    this.layerTree = layerInfo;
  },
  mounted() {
    // console.log('urlMap',urlMap);
    this.initMap();
    this.eventHandler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
  },
  methods: {
    initMap() {
      // agcim.scene.mapInit.createMap("map", {
      //   infoBox: false,
      //   shadows: true
      // });
      // var iframe = document.getElementsByClassName("cesium-infoBox-iframe")[0];
      // iframe.setAttribute(
      //   "sandbox",
      //   "allow-same-origin allow-scripts allow-popups allow-forms"
      // );
      // iframe.setAttribute("src", "");
      // // window.handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
      // window.viewer = CIM.viewer;
      //Viewer和CesiumWidget的区别是后者去掉控件，比如时间控件
      //window.viewer = new Cesium.CesiumWidget("map", {
      window.viewer = new Cesium.Viewer("map", {
        // contextOptions: {
        //     requestWebgl1: true,
        //   },
        navigation: false,
        infoBox: false,
        shadows: false,
      });
      viewer.scene.globe.enableLighting = false;
      viewer.scene.globe.depthTestAgainstTerrain = true;
      // window.splitViewer=initMap('map1')
      window.scene = viewer.scene;
      if (Cesium.FeatureDetection.supportsImageRenderingPixelated()) {
        //判断是否支持图像渲染像素化处理
        viewer.resolutionScale = window.devicePixelRatio;
      }
      viewer.scene.fxaa = true;
      viewer.scene.postProcessStages.fxaa.enabled = true;

      scene.debugShowFramesPerSecond = true;
      // viewer.bottomContainer.style.display = "none";
      // const silhouette = viewer.scene.postProcessStages.add(
      //   Cesium.PostProcessStageLibrary.createSilhouetteStage()
      // );
      // silhouette.uniforms.color = Cesium.Color.LIME;
      // window.silhouette = silhouette;
      // silhouette.enabled = true;
      // let handler;
      // function addMouseOver(stage) {
      //   handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
      //   handler.setInputAction(function (movement) {
      //     const pickedObject = viewer.scene.pick(movement.endPosition);
      //     console.log("pickedObject--", pickedObject);
      //     if (Cesium.defined(pickedObject)) {
      //       silhouette.selected = [pickedObject.primitive];
      //     } else {
      //       silhouette.selected = [];
      //     }
      //   }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
      // }
      // addMouseOver(silhouette);
      // var GeoJsonData = viewer.dataSources.add(
      //   Cesium.GeoJsonDataSource.load("/geoJson/china.json", {
      //     fill: Cesium.Color.PINK, //填充色
      //     stroke: Cesium.Color.HOTPINK, //轮廓颜色
      //     strokeWidth: 5, //轮廓宽度
      //   })
      // );
      // GeoJsonData.then(viewer.zoomTo(GeoJsonData));
      // window.GeoJsonData=GeoJsonData;
      let imageUrl =
        "http://t0.tianditu.gov.cn/img_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=98e5cadb6046ae58140df1c26d8f415b";
      let noteUrl =
        "http://t0.tianditu.gov.cn/cia_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=cia&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default.jpg&tk=98e5cadb6046ae58140df1c26d8f415b";
      // layerManagerClass.addWMTS(imageUrl,'sdfgd')
      // layerManagerClass.addWMTS(noteUrl,'4536345')
      const handler = new Cesium.ScreenSpaceEventHandler(scene.canvas);
      let preColor
      let preFeature
      handler.setInputAction(function (movement) {
        const feature = scene.pick(movement.endPosition);
        if(preFeature instanceof Cesium.Cesium3DTileFeature&&Cesium.defined(preColor) ){
          
          preFeature.color=preColor
        }
        preFeature=feature
        if (feature instanceof Cesium.Cesium3DTileFeature) {
          preColor=Cesium.Color.clone(feature.color)
          feature.color= Cesium.Color.MIDNIGHTBLUE;
        }
      }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
    },
    addWMTS() {
      viewer.imageryLayers.addImageryProvider(imageMap);
      viewer.imageryLayers.addImageryProvider(notesMap);
      var wmtsLayer = new Cesium.ImageryLayer(imageMap);
    },
    addTiles() {
      // let ag3DTilesLayer = new agcim.layer.Ag3DTilesLayer(viewer);
      // const tiles = ag3DTilesLayer.add(
      //   "/mars3d-max-shihua-3dtiles-master/tileset.json"
      // );
      // tiles.readyPromise.then(function(tileset) {
      //   viewer.scene.primitives.add(tileset);
      //   viewer.zoomTo(
      //     tileset,
      //     new Cesium.HeadingPitchRange(
      //       0.0,
      //       -0.5,
      //       tileset.boundingSphere.radius * 2.0
      //     )
      //   );
      // });
      const tileset = new Cesium.Cesium3DTileset({
        url: "/mars3d-max-shihua-3dtiles-master/tileset.json",
      });
      window.tileset = tileset;
      tileset.readyPromise.then(function (tileset) {
        viewer.scene.primitives.add(tileset);
        viewer.zoomTo(
          tileset,
          new Cesium.HeadingPitchRange(
            0.0,
            -0.5,
            tileset.boundingSphere.radius * 2.0
          )
        );
      });
    },
    addS3M() {
      let s3mLayer = new agcim.layer.AgS3MLayer(viewer);
      s3mLayer.add(
        // `${iserverUrl}/iserver/services/3D-JianHuaHongBeiMoXing2021-2/rest/realspace`,
        "http://jgbim.qhfct.com:9999/iserver/services/3D-JianHuaHongBeiMoXing2021-2/rest/realspace.jsonp"
      );
    },
    sunshine() {
      this.sunshineVisible = true;
    },
    shootAreaAnalysis() {
      this.visualAreaVisible = true;
    },
    translation() {
      var cartographic = Cesium.Cartographic.fromCartesian(
        tileset.boundingSphere.center
      );
      var surface = Cesium.Cartesian3.fromRadians(
        cartographic.longitude,
        cartographic.latitude,
        0.0
      );
      var offset = Cesium.Cartesian3.fromRadians(
        cartographic.longitude,
        cartographic.latitude,
        200
      );
      var translation = Cesium.Cartesian3.subtract(
        offset,
        surface,
        new Cesium.Cartesian3()
      );
      tileset.modelMatrix = Cesium.Matrix4.fromTranslation(translation);
    },
    snow() {
      if (this.postProcessStages) {
        this.postProcessStages.removeAll();
        this.postProcessStages = null;
        return;
      }
      viewer.scene.skyBox.show = true;
      viewer.scene.skyAtmosphere.show = true;

      var Snow = `
        uniform sampler2D colorTexture; //输入的场景渲染照片
          varying vec2 v_textureCoordinates;

          float snow(vec2 uv,float scale)
          {
              float time = czm_frameNumber / 60.0;
              float w=smoothstep(1.,0.,-uv.y*(scale/10.));if(w<.1)return 0.;
              uv+=time/scale;uv.y+=time*2./scale;uv.x+=sin(uv.y+time*.5)/scale;
              uv*=scale;vec2 s=floor(uv),f=fract(uv),p;float k=3.,d;
            p=.5+.35*sin(11.*fract(sin((s+p+scale)*mat2(7,3,6,5))*5.))-f;d=length(p);k=min(d,k);
            k=smoothstep(0.,k,sin(f.x+f.y)*0.01);
            return k*w;
        }

        void main(void){
            vec2 resolution = czm_viewport.zw;
            vec2 uv=(gl_FragCoord.xy*2.-resolution.xy)/min(resolution.x,resolution.y);
            vec3 finalColor=vec3(0);
            //float c=smoothstep(1.,0.3,clamp(uv.y*.3+.8,0.,.75));
            float c = 0.0;
            c+=snow(uv,30.)*.0;
            c+=snow(uv,20.)*.0;
            c+=snow(uv,15.)*.0;
            c+=snow(uv,10.);
            c+=snow(uv,8.);
            c+=snow(uv,6.);
            c+=snow(uv,5.);
            finalColor=(vec3(c)); //屏幕上雪的颜色
              gl_FragColor = mix(texture2D(colorTexture, v_textureCoordinates), vec4(finalColor,1), 0.5);  //将雪和三维场景融合
        }
          `;

      Cesium.PostProcessStageLibrary.createSnowStage = function () {
        var snow = new Cesium.PostProcessStage({
          name: "czm_snow",
          fragmentShader: Snow,
        });
        return snow;
      };

      this.postProcessStages = viewer.scene.postProcessStages;
      var snow = Cesium.PostProcessStageLibrary.createSnowStage();
      this.postProcessStages.add(snow);
    },
    showLayerTree() {
      this.$refs.layerManager.enter();
    },
    pickEntity() {
      this.eventHandler.setInputAction(
        this.pickLeft,
        Cesium.ScreenSpaceEventType.LEFT_CLICK
      );
    },
    pickLeft(e) {
      let picked = viewer.scene.pick(e.position);
      console.log("拾取====", picked);
    },
    flat() {
      this.eventHandler.setInputAction(
        this.flatClick,
        Cesium.ScreenSpaceEventType.LEFT_CLICK
      );
    },
    screen2degrees(position) {
      const res = scene.pickPosition(position);
      //将笛卡尔坐标转化为经纬度坐标
      const cartographic = Cesium.Cartographic.fromCartesian(res);
      const longitude = Cesium.Math.toDegrees(cartographic.longitude);
      const latitude = Cesium.Math.toDegrees(cartographic.latitude);
      const height = cartographic.height;
      return {
        x: longitude,
        y: latitude,
        z: height,
      };
    },
    flatClick(e) {
      var position = viewer.scene.pickPosition(e.position); //鼠标点击一次获取开始坐标
      const point = this.screen2degrees(e.position);
      this.points.push(point.x, point.y);
      this.flatExtent.push(position);
      console.log("点击=====", this.flatExtent);
      if (this.points.length === 8) {
        viewer.entities.add({
          name: "tempPolygon",
          polygon: {
            hierarchy: this.flatExtent,
            material: Cesium.Color.BLUE.withAlpha(0.5),
            height: 20,
            fill: false,
            outline: true,
            outlineColor: Cesium.Color.RED,
            //classificationType:1,
          },
        });
        this.startFlat();
      }
      if (this.flatExtent.length === 4) {
        // this.startFlat();
        // this.eventHandler.removeInputAction(
        //   Cesium.ScreenSpaceEventType.LEFT_CLICK
        // );
      }
    },
    startFlat() {
      let customShader = new Cesium.CustomShader({
        lightingModel: Cesium.LightingModel.UNLIT,
        uniforms: {
          u_point1: {
            type: Cesium.UniformType.VEC3,
            value: this.flatExtent[0],
          },
          u_point2: {
            type: Cesium.UniformType.VEC3,
            value: this.flatExtent[1],
          },
          u_point3: {
            type: Cesium.UniformType.VEC3,
            value: this.flatExtent[2],
          },
          u_point4: {
            type: Cesium.UniformType.VEC3,
            value: this.flatExtent[3],
          },
          u_isFlatten: {
            type: Cesium.UniformType.BOOL,
            value: true,
          },
          u_planeNormal: {
            type: Cesium.UniformType.VEC3,
            value: getNormal(this.flatExtent),
          },
        },
        vertexShaderText: [
          `
            //计算投影
            vec3 projectPointOntoPlane(vec3 normal,vec3 planeOrigin,vec3 position){
                vec3 v01= position - planeOrigin;
                float scale=dot(normal,v01);
               vec3 scaledNormal=normal*scale;
               vec3 p= position-scaledNormal;
               return p;
              }
              bool cross1(vec3 point1,vec3 point2,vec3 point3,vec3 point){
                   vec3 ab=point2-point1;
                    vec3 ac=point3-point1;
                    vec3 ap=point-point1;
                    vec3 v1=cross(ab,ac);
                    vec3 v2=cross(ab,ap);
                    return dot(v1,v2)>=0.0;
              }
              //判断是否在三角形内
              bool isInT(vec3 point1,vec3 point2,vec3 point3,vec3 point){
                bool scale1=cross1(point1,point2,point3,point);
                bool scale2=cross1(point2,point3,point1,point);
                bool scale3=cross1(point3,point1,point2,point);
                return scale1&&scale2&&scale3;
              }
              //判断是否在矩形内
              bool isInExtent(vec3 point1,vec3 point2,vec3 point3,vec3 point4,vec3 point){
                bool t1 = isInT(point1,point2,point3,point);
                bool t2 = isInT(point3,point4,point1,point);
                return t1||t2;
              }

              void vertexMain(VertexInput vsInput, inout vec3 positionMC){
                vec3 positionWC = (czm_model*vec4(positionMC,1.0)).xyz;
                vec3 positionOnPlane = projectPointOntoPlane(u_planeNormal,u_point1,positionWC);
                //计算a点的模型坐标
                vec3 position1MC=(czm_inverseModel*vec4(u_point1,1.0)).xyz;
                if(u_isFlatten && isInExtent(u_point1,u_point2,u_point3,u_point4,positionOnPlane)){

                  positionMC.z = position1MC.z+fract(positionMC.z)*0.01;
                }
              }
              `,
        ],
        fragmentShaderText: [
          `void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material){
            //material.diffuse = vec3(0.0, 0.0, 1.0);
            //material.diffuse.g = -fsInput.attributes.positionEC.z / 1.0e4;
            }`,
        ],
      });

      scene.primitives._primitives[0].customShader = customShader;
      //添加压平范围
      viewer.entities.add({
        polygon: {
          hierarchy: { positions: this.flatExtent },
          material: Cesium.Color.BLUE.withAlpha(0.5),
          height: 20,
          fill: false,
          outline: true,
          outlineColor: Cesium.Color.RED,
          //classificationType:1,
        },
      });
      //高亮选中楼层，将其它楼层变透明
      // selectedFloor();
      // function selectedFloor() {
      //   viewer.screenSpaceEventHandler.setInputAction(function onLeftClick(
      //     movement
      //   ) {
      //     let pickPosition = viewer.scene.pickPosition(movement.position);
      //     console.log(JSON.stringify(pickPosition));
      //   },
      //   Cesium.ScreenSpaceEventType.LEFT_CLICK);
      // }
      function getNormal(positions) {
        let ab = Cesium.Cartesian3.subtract(
          positions[1],
          positions[0],
          new Cesium.Cartesian3()
        );
        let ac = Cesium.Cartesian3.subtract(
          positions[2],
          positions[0],
          new Cesium.Cartesian3()
        );
        //计算平面的法线
        let planeNormal = Cesium.Cartesian3.cross(
          ab,
          ac,
          new Cesium.Cartesian3()
        );
        planeNormal = Cesium.Cartesian3.normalize(
          planeNormal,
          new Cesium.Cartesian3()
        );
        return planeNormal;
      }
    },
    draw() {
      let that = this;
      // 初始化绘制工具
      const Draw = new CesiumDraw({
        action(feature) {
          // 绘制完成后清除绘制工具，并将绘制结果存入features
          // 为feature起名
          feature.properties.title = `${feature.properties.type}_${
            this.features.length + 1
          }`;
          feature.properties.visible = true;
          that.features.unshift(feature);
          Draw.destroy();
          that.currentPlotType = "";
          that.$message({
            message: "绘制完成！",
            type: "success",
          });
          // 使用features数据统一绘制管理
          // that.addEntity(feature);
        },
      });
      Draw.changeMode("POLYGON", {
        color: "#e74f3c",
        opacity: 1,
        elevation: 19,
      });
    },
  },
};
</script>
<style lang="less" scoped>
.c {
  width: 100vw;
  height: 100vh;
}
#map {
  width: 100vw;
  height: 100vh;
}
.layerIcon {
  position: absolute;
  bottom: 300px;
  left: 30px;
  z-index: 9;
  cursor: pointer;
}
.btnContainer {
  position: absolute;
  top: 2vh;
  left: 5vw;
}
.enter-before {
  display: none;
}
</style>
